<?php

/**
 * Pwiff - PHP SWF Library
 *
 * LICENSE
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package    Pwiff
 * @subpackage Tags
 * @copyright  Copyright (c) 2010 Steven Harris
 * @license    http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version    $Id: Tag.php 5 2010-02-14 05:08:39Z indigo.sunrise $
 */

/**
 * Abstract tag class.
 *
 * @package    Pwiff
 * @subpackage Tags
 */
abstract class Pwiff_Tag
{
	/**
	 * The type ID for this tag.
	 *
	 * @var int
	 */
	protected $pwiffTag = null;
	
	/**
	 * The environment object.
	 * 
	 * @var Pwiff_Environment
	 */
	protected $pwiffEnv = null;
	
	/**
	 * Constructor. Sets the environment.
	 *
	 * @param  Pwiff_Environment $env
	 */
	public function __construct(Pwiff_Environment $env)
	{
		$this->setEnvironment($env);
	}
	
	/**
	 * Sets the environment object.
	 *
	 * @param  Pwiff_Environment $env
	 * @return Pwiff_Tag
	 */
	public function setEnvironment(Pwiff_Environment $env)
	{
		$this->pwiffEnv = $env;
		return $this;
	}
	
	/**
	 * Gets the environment object.
	 *
	 * @return Pwiff_Environment
	 */
	public function getEnvironment()
	{
		return $this->pwiffEnv;
	}
	
	/**
	 * Gets the type ID for this tag.
	 *
	 * @return int
	 */
	public function getTagType()
	{
		return $this->pwiffTag & 0x3ff;
	}
	
	/**
	 * Gets the length of the tag's data.
	 *
	 * @return int
	 */
	abstract public function getTagLength();
	
	/**
	 * Writes the tag to the given output instance. This parent class
	 * handles the record header, while subclasses handle the tag data.
	 *
	 * @param  Pwiff_Output $out
	 */
	public function write(Pwiff_Output $out)
	{
		// Write the record header
		$length = $this->getTagLength();
		$header = $this->getTagType() << 6;
		
		if ($length < 63) {
			$out->writeUI16($header | ($length & 0x3f));
		}
		else {
			$out->writeUI16($header | 0x3f);
			$out->writeSI32($length);
		}
	}
}
